package com.hsj.busmanager.controller;

import com.hsj.busmanager.api.UserBean;
import com.hsj.busmanager.api.UserConst;
import com.hsj.busmanager.service.NewsService;
import com.hsj.busmanager.service.UserService;
import com.hsj.busmanager.util.R;
import com.hsj.busmanager.util.RandomValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private NewsService newsService;

    @Autowired
    private UserService userService;

        @RequestMapping(value = "/tologin")
        @ResponseBody
        public R tologin(UserBean user, String code, HttpServletRequest request){


            if(StringUtils.isEmpty(user.getUserName())){
                return R.error("用户名不能为空");
            }
            if(StringUtils.isEmpty(user.getPassword())){
                return R.error("密码不能为空");
            }
            if(StringUtils.isEmpty(code)){
                return R.error("验证码不能为空");
            }

            //验证码校验
            boolean check_code = checkCode(code,request);
            if(!check_code){
                return R.error("验证码错误");
            }

            //用户名和密码验证
           UserBean curren_user = checkuser(user.getUserName(),user.getPassword());

            if(curren_user == null){
                return R.error("用户名或者密码错误！");
            }

            request.getSession().setAttribute("user",curren_user);

            //根据用户类型分配URL
            String type = curren_user.getType();
            String url = "";
           if(UserConst.DRIVER_TYPE.equals(type)){
               //司机
                url = "/driver/index";
           }else if(UserConst.ADMIN_TYPE.equals(type)){
                //管理员
               url = "/admin/index";
           }else if(UserConst.SUPER_ADMIN_TYPE.equals(type)){
//               url = "/superAdmin/index";
               url = "/admin/index";
           }else{
               return R.error("用户类型错误！");
           }

           return  R.ok("url",url);
        }

    private UserBean checkuser(String userName, String password) {

       return userService.check(userName,password);

    }


    private boolean checkCode(String code,HttpServletRequest request) {

            String right_code = request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY).toString();

            return right_code.equals(code);

    }

}
